<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item prop="sn">
        <el-input
          v-model="queryParams.sn"
          placeholder="请输入商品编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择分类" clearable>
          <el-option
            v-for="dict in categoryOptions"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="isOnsale">
        <el-select v-model="queryParams.isOnsale" placeholder="请选择是否上架" clearable>
          <el-option
            v-for="dict in dict.type.sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="isWastage">
        <el-select v-model="queryParams.isWastage" placeholder="请选择是否损耗" clearable>
          <el-option
            v-for="dict in dict.type.sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="wastageType">
        <el-select v-model="queryParams.wastageType" placeholder="请选择损耗类型" clearable>
          <el-option
            v-for="dict in dict.type.sys_wastage_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:item:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:item:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-thumb"
          size="mini"
          :disabled="multiple"
          @click="handleBuy"
          v-hasPermi="['system:item:buy']"
        >购买
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:item:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:item:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="itemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center"/>
      <el-table-column label="id" width="50" align="center" prop="id"/>
      <el-table-column label="图片" align="center" prop="picture">
        <template slot-scope="scope">
          <image-preview :src="scope.row.picture" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="编号" width="50" align="center" prop="sn"/>
      <el-table-column label="名称" align="center" prop="name"/>
      <el-table-column label="分类" align="center" prop="categoryName"/>
      <el-table-column label="价格" align="center" prop="price"/>
      <el-table-column label="库存" align="center" prop="stock">
        <template slot-scope="scope">
          <span v-if="scope.row.stock<10" style="color: red">{{scope.row.stock}}</span>
          <span v-else>{{scope.row.stock}}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否上架" align="center" prop="isOnsale">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isOnsale"/>
        </template>
      </el-table-column>
      <el-table-column label="是否损耗" align="center" prop="isWastage">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isWastage"/>
        </template>
      </el-table-column>
      <el-table-column label="损耗类型" align="center" prop="wastageType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_wastage_type" :value="scope.row.wastageType"/>
        </template>
      </el-table-column>
      <el-table-column label="销量计数" align="center" prop="sellCount"/>
      <el-table-column label="上架时间" align="center" prop="onsaleTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.onsaleTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-thumb"
            @click="handleBuy(scope.row)"
            v-hasPermi="['system:item:buy']"
          >购买
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:item:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:item:remove']"
          >删除
          </el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:user:resetPwd', 'system:user:edit']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleWastage" icon="el-icon-key"
                                v-hasPermi="['system:user:wastage']">确认损耗
              </el-dropdown-item>
              <el-dropdown-item command="handleOnsale" icon="el-icon-circle-check"
                                v-hasPermi="['system:user:onsale']">上架/下架
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品编号" prop="sn">
          <el-input v-model="form.sn" placeholder="请输入商品编号"/>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择商品分类">
            <el-option
              v-for="dict in categoryOptions"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片" prop="picture">
          <image-upload v-model="form.picture" :limit="1"/>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入描述"/>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="form.price" :precision="2" :min="0" :max="9999999" label="请输入价格"></el-input-number>
        </el-form-item>
        <el-form-item label="库存数量" prop="stock">
          <el-input-number v-model="form.stock" :min="0" :max="9999999" label="请输入数量"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--   确认损耗弹出框 -->
    <el-dialog title="确认损耗" :visible.sync="open2" width="500px" append-to-body>
      <el-form ref="form" :model="form2" :rules="rules2" label-width="80px">
        <el-form-item label="损耗类型" prop="wastageType">
          <el-select v-model="form2.wastageType" placeholder="请选择损耗类型">
            <el-option
              v-for="dict in dict.type.sys_wastage_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm2">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listItem, getItem, delItem, addItem, updateItem, buyItem} from "@/api/system/item";
import {listCategory} from "@/api/system/category";

export default {
  name: "Item",
  dicts: ['sys_wastage_type', 'sys_yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSysItemCategory: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      itemList: [],
      // 商品分类表格数据
      sysItemCategoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open2: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        sn: null,
        name: null,
        isOnsale: null,
        wastageType: null,
        isWastage: null,
      },
      // 表单参数
      form: {},
      form2: {},
      // 表单校验
      rules: {
        sn: [{required: true, message: "商品编号不能为空", trigger: "blur"}],
        name: [{required: true, message: "名称不能为空", trigger: "blur"}],
        categoryId: [{required: true, message: "商品分类不能为空", trigger: "blur"}],
        price: [{required: true, message: "价格不能为空", trigger: "blur"}],
        stock: [{required: true, message: "库存数量不能为空", trigger: "blur"}],
      },
      rules2: {wastageType: [{required: true, message: "损耗类型不能为空", trigger: "blur"}],},
      categoryOptions: [],
    };
  },
  created() {
    this.getList();
    this.getCategoryOptions()
  },
  methods: {
    getCategoryOptions() {
      listCategory({pageNum: 1, pageSize: 1000}).then(res => {
        this.categoryOptions = res.rows
      })
    },
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      listItem(this.queryParams).then(response => {
        this.itemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.open2 = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        categoryId: null,
        sn: null,
        name: null,
        picture: null,
        description: null,
        price: null,
        stock: null,
        isOnsale: null,
        wastageType: null,
        wastageTime: null,
        isWastage: null,
        sellCount: null,
        onsaleTime: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.sysItemCategoryList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleWastage":
          this.handleWastage(row);
          break;
        case "handleOnsale":
          this.handleOnsale(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getItem(id).then(response => {
        this.form = response.data;
        this.sysItemCategoryList = response.data.sysItemCategoryList;
        this.open = true;
        this.title = "修改商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.sysItemCategoryList = this.sysItemCategoryList;
          if (this.form.id != null) {
            updateItem(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addItem(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品编号为"' + ids + '"的数据项？').then(function () {
        return delItem(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 购买按钮操作 */
    handleBuy(row) {
      const ids = row.id || this.ids;
      let sum = 0;
      let flag = false
      if (ids.length > 1) {
        ids.forEach(id => {
          this.itemList.forEach(item => {
            if (item.id === id) {
              if (item.stock <= 0) {
                flag = true
                this.$modal.msgError("商品" + item.name + "库存不足，购买失败！");
                return
              }
              sum += item.price
            }
          })
        })
      } else {
        if (row.stock <= 0) {
          this.$modal.msgError("商品" + row.name + "库存不足，购买失败！");
          return
        }
        sum = row.price
      }
      if (!flag) {

        this.$modal.confirm('是否确认购买商品编号为"' + ids + '"的数据项？总价为：' + sum + '元').then(function () {
          return buyItem(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("购买成功");
        }).catch(() => {
        });
      }
    },
    /** 确认损耗按钮操作 */
    handleWastage(row) {
      if (row.isWastage == 'Y') {
        this.$modal.msgError("商品已损耗");
        return
      }
      this.open2 = true
      this.form2.id = row.id
    },
    /** 提交按钮 */
    submitForm2() {
      if (this.form2.wastageType == undefined || this.form2.wastageType == null) {
        this.$modal.msgError("请选择损耗类型！");
        return;
      }
      this.form2.isWastage = 'Y'
      updateItem(this.form2).then(response => {
        this.$modal.msgSuccess("确认成功");
        this.open2 = false;
        this.getList();
      });
    },
    /** 上架/下架按钮操作 */
    handleOnsale(row) {
      let content = "下架"
      let isOnsale = ""
      if (row.isOnsale === 'N') {
        isOnsale = 'Y'
        content = '上架'
      } else {
        isOnsale = 'N'
      }
      this.$modal.confirm('是否确认' + content + '商品编号为"' + row.id + '"的数据项？').then(function () {
        return updateItem({
          id: row.id,
          isOnsale: isOnsale
        });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(content + "成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/item/export', {
        ...this.queryParams
      }, `item_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
